package com.fanjun.learning.multithread.Activity_Object_Pattern;


/**
 * 活性队列类,提供存储请求的消息队列
 */
public class ActivationQueue {
    private static final int MAX_METHOD_REQUEST = 100;
    private final Request[] requestQueue;
    private int tail ;
    private int head ;
    private int count;

    public ActivationQueue(){
        this.requestQueue = new Request[MAX_METHOD_REQUEST];
        this.tail = 0;
        this.head = 0;
        this.count = 0;
    }

    public synchronized void putRequest(Request request) {
        while (count >= requestQueue.length){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        requestQueue[tail] = request;
        tail = (tail + 1) % requestQueue.length;
        count++;
        notifyAll();
    }

    public synchronized Request takeRequest() {
        while (count <= 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Request request = requestQueue[head];
        head = (head + 1) % requestQueue.length;
        count--;
        notifyAll();

        return request;
    }

    public synchronized Request[] takeRequestList(){
        return requestQueue;
    }
}
